package src.stack;

/**
 * @author Dream
 */
public class ArrayStack<T> {
    private final Object[] pen;
    private int topPointer;//栈顶指针

    // 数组现实的栈
    public ArrayStack(int length) {
        pen = new Object[length];
    }

    // 入栈
    public void push(T t) {
        if (t == null) {
            System.out.println("插入失败：元素不能为空");
            return;
        }
        try {
            pen[topPointer] = t;
            ++topPointer;//成功后自增
        } catch (Exception e) {
            System.out.println("插入失败，栈已满");
        }
    }

    // 出栈
    public T pop() {
        if (isEmpty()) {
            return null;
        }
        try {
            T t = (T) pen[topPointer - 1];
            pen[topPointer - 1] = null;//取出元素后清空
            topPointer--;//成功后
            return t;
        } catch (Exception e) {
            System.out.println("出栈失败，栈已空");
        }
        return null;
    }

    //查看栈顶元素
    public T peek() {
        if (isEmpty()) {
            return null;
        }
        try {
            return (T) pen[topPointer - 1];
        } catch (Exception e) {
            System.out.println("查看失败，栈已空");
        }
        return null;
    }

    public int size() {
        return topPointer;
    }

    public boolean isEmpty() {
        if (topPointer == 0) {
            return true;
        }
        return false;
    }


}
